<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryPageApi, addCarApi, queryInfoApi, updateCarApi, deleteCarApi} from '@/api/car'
import { queryAllApi as queryAllUserApi } from '@/api/user'

//用户列表数据
const userList = ref([])

const searchCar = ref({
  brand: '',
  userName: ''
})

//声明token
const token = ref('')

onMounted(async () => {
  handleSearch()

  //加载所有用户数据
  const result = await queryAllUserApi();
  if(result.code){
    userList.value = result.data
  }

  //加载localStorage存储的登录信息
  const loginUser =  localStorage.getItem('loginUser');
  if(loginUser){
    token.value = JSON.parse(loginUser).token
  }
})

//查询车辆
const handleSearch = async () => {
  console.log('Search:', searchCar.value)
  const result = await queryPageApi(searchCar.value.brand, searchCar.value.userName, '', currentPage.value, pageSize.value);
  if(result.code){
    carList.value = result.data.rows
    total.value = result.data.total
  }
}

const handleReset = () => {
  // 清空表单
  searchCar.value = {
    brand: '',
    userName: ''
  }
  handleSearch()
}

// 示例数据
const carList = ref([])

// 分页配置
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}

// 操作处理
const handleEdit = async (id) => {
  const result = await queryInfoApi(id);
  if(result.code){
    dialogVisible.value = true
    dialogTitle.value = '修改车辆'
    car.value = result.data
  }
  carFormRef.value.resetFields()
}

// 删除单个车辆
const handleDelete = async (id) => {
  //弹出一个确认框, 如果确认, 就删除;
  ElMessageBox.confirm('确定删除该车辆吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 删除车辆
    const result = await deleteCarApi(id);
    if(result.code){
      ElMessage.success('删除车辆成功')
      handleSearch()
    }else{
      ElMessage.error(result.msg)
    }
  })
}

//新增车辆
const addCar = () => {
  dialogVisible.value = true
  dialogTitle.value = '新增车辆'
  car.value = {
    brand: '',
    model: '',
    plateNumber: '',
    year: '',
    userId: '',
    remark: ''
  }
  carFormRef.value.resetFields()
}


//新增/修改表单
const carFormRef = ref(null)
const car = ref({
  brand: '',
  model: '',
  plateNumber: '',
  year: '',
  userId: '',
  remark: ''
})

//表单校验规则
const rules = ref({
  brand: [
    { required: true, message: '请输入品牌', trigger: 'blur' },
    { min: 2, max: 20, message: '品牌长度应在2到20个字符之间', trigger: 'blur' }
  ],
  model: [
    { required: true, message: '请输入型号', trigger: 'blur' },
    { min: 2, max: 30, message: '型号长度应在2到30个字符之间', trigger: 'blur' }
  ],
  plateNumber: [
    { required: true, message: '请输入车牌号', trigger: 'blur' },
    { pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/, message: '请输入有效的车牌号', trigger: 'blur' }
  ],
  year: [
    { required: true, message: '请输入生产年份', trigger: 'blur' },
    { pattern: /^[0-9]{4}$/, message: '请输入有效的年份（4位数字）', trigger: 'blur' }
  ],
  userId: [
    { required: true, message: '请选择用户', trigger: 'change' }
  ]
});

// 控制弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('新增车辆')

//保存车辆信息
const save = async () => {
  carFormRef.value.validate(async valid => {
    if(valid){ // 校验通过
      let result ;
      if(car.value.id){ //存在ID, 修改
        result = await updateCarApi(car.value);
      }else { //不存在ID, 新增
        result = await addCarApi(car.value);
      }
      if(result.code){
        ElMessage.success('操作成功')
        dialogVisible.value = false
        handleSearch()
      }else {
        ElMessage.error(result.msg)
      }
    }
  })
}

// 存储选中的 ID
const selectedIds = ref([]);

// 处理复选框选择变化的函数
function handleSelectionChange(selection) {
  const ids = selection.map(item => item.id);
  selectedIds.value = ids;
}

//批量删除
const deleteByIds = async () => {
  if(selectedIds.value.length === 0){
    ElMessage.warning('请先选择要删除的车辆')
    return
  }
  
  //弹出一个确认框, 如果确认, 就删除;
  ElMessageBox.confirm('确定删除选中车辆吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 删除车辆
    const result = await deleteCarApi(selectedIds.value);
    if(result.code){
      ElMessage.success('删除车辆成功')
      handleSearch()
    }else{
      ElMessage.error(result.msg)
    }
  })
}
</script>

<template>
  <h1>车辆管理</h1> <br>
  <el-form :inline="true" :model="searchCar">
    <el-form-item label="品牌">
      <el-input v-model="searchCar.brand" placeholder="请输入车辆品牌"></el-input>
    </el-form-item>

    <el-form-item label="用户名">
      <el-input v-model="searchCar.userName" placeholder="请输入用户姓名"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">清空</el-button>
    </el-form-item>
  </el-form>


  <el-button type="primary" @click="addCar"> + 新增车辆</el-button>
  <el-button type="danger" @click="deleteByIds"> - 批量删除</el-button>
  <br><br>

  <!-- 表格 -->
  <el-table :data="carList" border style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" align="center"></el-table-column>
    <el-table-column type="index" label="序号" width="100" align="center"/>
    <el-table-column prop="brand" label="品牌" width="120" align="center"></el-table-column>
    <el-table-column prop="model" label="型号" width="150" align="center"></el-table-column>
    <el-table-column prop="plateNumber" label="车牌号" width="150" align="center"></el-table-column>
    <el-table-column prop="year" label="生产年份" width="120" align="center"></el-table-column>
    <el-table-column prop="userName" label="用户姓名" width="120" align="center"></el-table-column>
    <el-table-column prop="updateTime" label="最后操作时间" width="210" align="center"></el-table-column>
    <el-table-column label="操作" fixed="right" align="center">
      <template #default="scope">
        <el-button size="small" type="primary" @click="handleEdit(scope.row.id)">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <br>

  <!-- 分页 -->
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="currentPage"
    :page-sizes="[5, 10, 20, 30]"
    :page-size="pageSize"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
  >
  </el-pagination>

  <!-- 新增/修改车辆的对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form ref="carFormRef" :model="car" :rules="rules" label-width="100px">
        <!-- 基本信息 -->
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="car.brand" placeholder="请输入车辆品牌，2-20个字"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="型号" prop="model">
              <el-input v-model="car.model" placeholder="请输入车辆型号，2-30个字"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="车牌号" prop="plateNumber">
              <el-input v-model="car.plateNumber" placeholder="请输入车牌号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 第四行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产年份" prop="year">
              <el-input v-model="car.year" placeholder="请输入4位数字的生产年份"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属用户" prop="userId">
              <el-select v-model="car.userId" placeholder="请选择用户" style="width: 100%;">
                <el-option v-for="user in userList" :key="user.id" :label="user.name" :value="user.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="car.remark" placeholder="请输入备注信息" type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </span>
      </template>
    </el-dialog>
</template>

<style scoped>
.el-form-item {
  margin-bottom: 16px;
}
</style>